﻿using System;
using RssReader.Common;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Search;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Grid Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace RssReader
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// An overview of the Grid Application design will be linked to in future revisions of
    /// this template.
    /// </summary>
    sealed partial class App : Application
    {
        public static string ItemsKeyString = "items";
        public static Color ARGBColor = Color.FromArgb(255, 220, 235, 221);
        public static SettingsCommandHelper SettingsCommandHelper = new SettingsCommandHelper();
        public static new App Current
        {
            get { return Application.Current as App; }
        }

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeComponent();
            Suspending += OnSuspending;            
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
            #if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active

            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                //Associate the frame with a SuspensionManager key                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
                // Set the default language
                rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                var extendedSplash = new ExtendedSplashScreen(e.SplashScreen, false);
                Window.Current.Content = extendedSplash;
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        void OnSuspending(object sender, SuspendingEventArgs args)
        {
            SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
            SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        protected override void OnSearchActivated(SearchActivatedEventArgs args)
        {
            var searchResultsPage = new Frame();
            var rootFrame = Window.Current.Content as Frame;
            Type currentSourcePageType = Current_source_page_type(rootFrame);

            this.Ensure_activated(args, searchResultsPage);
            var tuple = new Tuple<string, Type>(args.QueryText, currentSourcePageType);

            if (searchResultsPage.Content == null)
                searchResultsPage.Navigate(typeof (SearchResultsPage), tuple);
        }

        protected override void OnWindowCreated(WindowCreatedEventArgs args)
        {
            // Register QuerySubmitted handler for the window at window creation time and only registered once
            // so that the app can receive user queries at any time.
            SearchPane.GetForCurrentView().QuerySubmitted += App_QuerySubmitted;
            SearchPane.GetForCurrentView().ShowOnKeyboardInput = true;
        }

        private async void Ensure_activated(SearchActivatedEventArgs args, Frame searchResultsPage)
        {
            var searchPane = SearchPane.GetForCurrentView();
            searchPane.PlaceholderText = "Enter Your Search Here!";
            searchPane.SearchHistoryEnabled = true;

            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Activate();
                return;
            }

            SuspensionManager.RegisterFrame(searchResultsPage, "AppFrame");
            

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                await SuspensionManager.RestoreAsync();
            }

            Window.Current.Content = searchResultsPage;
            Window.Current.Activate();
        }

        void App_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;
            Type currentSourcePageType = Current_source_page_type(rootFrame);
            var tuple = new Tuple<string, Type>(args.QueryText, currentSourcePageType);
            
            if (rootFrame != null) rootFrame.Navigate(typeof(SearchResultsPage), tuple);
        }

        public static Type Current_source_page_type(Frame rootFrame)
        {
            Type currentSourcePageType = null;
            if (rootFrame != null) currentSourcePageType = rootFrame.CurrentSourcePageType;
            return currentSourcePageType;
        }
    }
}
